package com.pay.game.central.web.service;

import com.github.pagehelper.Page;
import com.pay.game.central.utils.DateTimeUtil;
import com.pay.game.central.web.bean.Rent;
import com.pay.game.central.web.bean.Settlement;
import com.pay.game.central.web.bean.Store;
import com.pay.game.central.web.mapper.RentMapper;
import com.pay.game.central.web.mapper.SettlementMapper;
import com.pay.game.central.web.mapper.StoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SettlementService {

    @Autowired
    private SettlementMapper settlementMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private RentMapper rentMapper;

    public Page<Settlement> list(String rootUserId,
                                 boolean showDescendant,
                                 String storeId,
                                 String storeName,
                                 String startDate,
                                 String endDate){
        return settlementMapper.list(rootUserId,showDescendant,storeId,storeName,startDate.equals(endDate),startDate,endDate);
    }

    /**
     * 获取用户 当前跑分,利润,下级贡献 and 一段时间跑分,利润,下级贡献
     */
    public Map<String,Object> countInfo(String userId,String startDate, String endDate, String today){
        Date date = new Date(DateTimeUtil.parseDate(today, DateTimeUtil.DATE_PATTERN).getTime());
        Map<String, Object> map = new HashMap<>();
        //获取跑分统计
        int periodScore = 0;
        int periodInterest = 0;
        List<Settlement> settlements = settlementMapper.listPeriod(userId,startDate,endDate);
        for (Settlement s: settlements) {
            periodScore = periodScore + s.getRun_score();
            periodInterest = periodInterest + s.getValue();
        }
        int todayRent = 0;
        int periodRent = 0;
        List<Rent> rents = rentMapper.queryPeriod(userId, startDate, endDate);
        for (Rent r: rents) {
            periodRent  = periodRent + r.getValue();
            if (r.getDate().equals(date)) todayRent = todayRent + r.getValue();
        }
        int currentScore = storeMapper.queryRunStoreByUserId(userId)
                .stream()
                .mapToInt(Store::getUsed_score)
                .sum();
        map.put("periodScore", periodScore);
        map.put("periodInterest", periodInterest);
        map.put("currentScore", currentScore);
        map.put("todayRent", todayRent);
        map.put("periodRent", periodRent);
        return  map;
    }

}
